import reqwest from  './reqwest';
import {
    message
} from 'antd';
import Config from '../config';

var HOST = Config.host;
var ALIAS = document.body.getAttribute('j-data-alias');

if (typeof __devMode !== 'undefined') {
    HOST = Config.host_dev;
}

function _Get(url, data, success, fail) {
    _request('get', url, data, success, fail);
}

function _Post(url, data, success, fail) {
    _request('post', url, data, success, fail);
}

function _request(method, url, data, success, fail) {
    var requestObj;
    var header = {};
    var paramsStr = '';

    url = HOST + url + '?alias=' + ALIAS;
    method = (method || 'get').toLowerCase();
    data = data || {};

    requestObj = {
        method: method,
    };

    if (method == 'get') {
        Object.keys(data).forEach(function (key) {
            var val = data[key];

            if (val instanceof Array) {
                val.forEach(function (v) {
                    paramsStr += '&' + key + '[]=' + v;
                });
            } else {
                paramsStr += '&' + key + '=' + val;
            }
        });
        url = url + paramsStr;
    } else if (method == 'post') {
        requestObj.data = data;
    }

    reqwest({
        url: url,
        ...requestObj,
        crossOrigin: typeof __devMode !== 'undefined',
        withCredentials: typeof __devMode !== 'undefined',
    }).then(function (res) {
        var data = JSON.parse(res);

        if (data.code == 0) {
            typeof success == "function" && success(data);
        } else {
            typeof fail == "function" && fail(data);
            if (data.msg) {
                message.warning(data.msg);
            }
        }
    }, function (res) {
        typeof fail == "function" && fail(res);
        console.log('failed', res);
    }).catch(function (ex) {
        typeof fail == "function" && fail(ex);
        console.log('parsing failed', ex);
    });

}
var Ajax = {
    P: _Post,
    G: _Get
};

export default Ajax;